package com.audaque.springboot.foshanupload.gateway.factory;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author zgb
 * @desc 注意：自定义过滤器的命名应该为：***GatewayFilterFactory
 * @date 2023-08-01 15:46:38
 */
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {

    public MyParamGatewayFilterFactory() {
        super(Config.class);
    }
    @Override
    public List<String> shortcutFieldOrder() {
        //读取配置文件中的参数值，然后赋值到配置实体类属性上
        return Arrays.asList("param");
    }
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            if (request.getQueryParams().containsKey(config.param)) {
                request.getQueryParams().get(config.param)  //get方法获取的是一个List，而且List中只有一个值
                        .forEach(value ->
                                System.out.printf("----------局部过滤器-----%s = %s-----", config.param, value));
            }
            return chain.filter(exchange);
        };
    }
    public static class Config {
        // 对应在配置过滤器的时候指定的参数名，如name
        private String param;
        public String getParam() {
            return param;
        }
        public void setParam(String param) {
            this.param = param;
        }
    }
}
